package myJs.cps

import myJs.myPkg.reactBootstrap.{OverlayTrigger, Popover}
import myJs.myPkg.reactHookForm._

import scala.scalajs.js
import myJs.Implicits._
import org.scalajs.dom.html
import japgolly.scalajs.react.ScalaFnComponent
import japgolly.scalajs.react.vdom.all._
import cats.effect._
import japgolly.scalajs.react.util.EffectCatsEffect._

object InputInlineCp {

  case class Props(
      name: String,
      registerOptions: RegisterOptions = RegisterOptions(),
      onChange: String => SyncIO[Unit],
      value: String = "",
      label: String,
      labelWidth: Int = 2,
      inputWidth: Int = 4,
      readOnly: Boolean = false,
      show: Boolean = true,
      placeholder: String = "",
      questionInfo: js.UndefOr[String] = js.undefined,
      onFocus: js.UndefOr[html.Input => Unit] = js.undefined
  ) {
    @inline def render = {
      component(this)
    }
  }

  val component = ScalaFnComponent[Props] { props =>
    val formState = ReactHookForm.useFormState(options =
      UseFormStateOptions(
        name = props.name
      )
    )

    div(
      display.none.unless(props.show),
      classSet1(s"form-group ", "has-error" -> formState.errors.isDefinedAt(props.name)),
      label(
        className := s"control-label col-sm-${props.labelWidth}",
        s"${props.label}",
        props.questionInfo.map { questionInfo =>
          val popover = Popover(id = "popover-basic")(
            Popover.Header("说明"),
            Popover.Body(
              questionInfo
            )
          )
          OverlayTrigger(
            placement = "auto",
            trigger = js.Array("hover", "focus"),
            overlay = popover.rawElement
          )(
            span(
              a(`type` := "button", i(className := "fa fa-question-circle-o"))
            )
          )
        },
        ":"
      ),
      div(
        className := s"col-sm-${props.inputWidth}",
        PureInputCp
          .Props(
            name = props.name,
            registerOptions = props.registerOptions,
            onChange = props.onChange,
            value = props.value,
            readOnly = props.readOnly,
            placeHolder = props.placeholder,
            onFocus = props.onFocus
          )
          .render
      )
    )

  }

}
